package com.digicom.api.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.digicom.common.constant.Constants;
import com.digicom.common.entity.Comment;
import com.digicom.common.entity.User;
import com.digicom.common.core.domain.ApiResponse;
import com.digicom.common.core.utils.SecurityUtils;
import com.digicom.common.core.utils.ServletUtils;
import com.digicom.service.comment.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 评论接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 获取文章评论列表
     */
    @GetMapping("/list/{articleId}")
    public ApiResponse<Page<Comment>> list(@PathVariable Long articleId,
                                           @RequestParam(defaultValue = "1") Integer pageNum,
                                           @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Comment> page = new Page<>(pageNum, pageSize);
        Page<Comment> comments = commentService.listArticleComments(articleId, page);
        return ApiResponse.success(comments);
    }

    /**
     * 添加评论
     */
    @PostMapping("/add")
    public ApiResponse<Long> add(@RequestBody Comment comment) {
        // 设置当前用户ID和名称
        comment.setUserId(SecurityUtils.getUserId());
        comment.setUserName(SecurityUtils.getUsername());
        
        // 添加评论
        Long commentId = commentService.addComment(comment);
        return ApiResponse.success(commentId);
    }

    /**
     * 回复评论
     */
    @PostMapping("/reply")
    public ApiResponse<Long> reply(@RequestBody Comment comment) {
        // 设置当前用户ID和名称
        comment.setUserId(SecurityUtils.getUserId());
        comment.setUserName(SecurityUtils.getUsername());
        
        // 回复评论
        Long commentId = commentService.replyComment(comment);
        return ApiResponse.success(commentId);
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/{commentId}")
    public ApiResponse<Boolean> delete(@PathVariable Long commentId) {
        Long userId = SecurityUtils.getUserId();
        boolean result = commentService.deleteComment(commentId, userId);
        return ApiResponse.success(result);
    }

    /**
     * 获取用户评论列表
     */
    @GetMapping("/user")
    public ApiResponse<Page<Comment>> userComments(@RequestParam(defaultValue = "1") Integer pageNum,
                                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        Long userId = SecurityUtils.getUserId();
        Page<Comment> page = new Page<>(pageNum, pageSize);
        Page<Comment> comments = commentService.listUserComments(userId, page);
        return ApiResponse.success(comments);
    }
}
